#include "cmdsingle.h"
#include <QProcess>
#include <QTextCodec>
#include <QByteArray>
#include <iostream>
#include <QTime>
#include <QCoreApplication>
#include <QDebug>

CmdSingle::CmdSingle()
{

}

static void msleep(int time_ms){
    QTime timing;
    timing.start();
    while (timing.elapsed() < time_ms)
    {
        QCoreApplication::processEvents();
    }
}

QString CmdSingle::StartOnecmd(QString cmdstr, int timeouts)
{
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QProcess    cmdgExec;
    QStringList options;
    QString cmdOutstr;

    options << "-c";
    options << cmdstr;
    cmdgExec.start("/bin/bash", options);

    int count_i = 0;
    while (true) {
        msleep(10);
        count_i++;
        QString outstr = codec->toUnicode(cmdgExec.readAllStandardOutput());  //读取运行过程中的输出值
        outstr.append(codec->toUnicode(cmdgExec.readAllStandardError()));

        // qDebug() << "###" << outstr << "###";
        cmdOutstr.append(outstr);

        if(cmdgExec.state() == QProcess::NotRunning){
            break;
        }
        if(count_i*10 >= timeouts){
            break;
        }
    }
    return cmdOutstr;
}
